import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userRole = ref(localStorage.getItem('userRole') || '')
  const userId = ref(parseInt(localStorage.getItem('userId') || '0'))
  const username = ref(localStorage.getItem('username') || '')
  
  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const isAdmin = computed(() => userRole.value === 'ADMIN')
  
  // 设置登录信息
  function setLoginInfo(loginData) {
    if (loginData.token) {
      token.value = loginData.token
      localStorage.setItem('token', loginData.token)
    }
    
    if (loginData.role) {
      userRole.value = loginData.role
      localStorage.setItem('userRole', loginData.role)
    }
    
    if (loginData.id) {
      userId.value = loginData.id
      localStorage.setItem('userId', loginData.id)
    }
    
    if (loginData.username) {
      username.value = loginData.username
      localStorage.setItem('username', loginData.username)
    }
  }
  
  // 清除登录信息
  function clearLoginInfo() {
    token.value = ''
    userRole.value = ''
    userId.value = 0
    username.value = ''
    
    localStorage.removeItem('token')
    localStorage.removeItem('userRole')
    localStorage.removeItem('userId')
    localStorage.removeItem('username')
  }
  
  return { 
    token,
    userRole,
    userId,
    username,
    isLoggedIn,
    isAdmin,
    setLoginInfo,
    clearLoginInfo
  }
}) 